package com.qinggeng.project.api.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.qinggeng.common.constant.Constants;
import com.qinggeng.common.constant.UserConstants;
import com.qinggeng.common.enums.CommonEnum;
import com.qinggeng.common.enums.MessageTypeEnum;
import com.qinggeng.common.enums.ShowTypeEnum;
import com.qinggeng.common.enums.UserTypeEnum;
import com.qinggeng.common.utils.DateUtils;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.framework.aspectj.lang.annotation.Log;
import com.qinggeng.framework.aspectj.lang.enums.BusinessType;
import com.qinggeng.framework.redis.RedisCache;
import com.qinggeng.framework.security.LoginUser;
import com.qinggeng.framework.web.controller.BaseController;
import com.qinggeng.framework.web.domain.AjaxResult;
import com.qinggeng.project.api.dto.*;
import com.qinggeng.project.api.security.annotation.LoginRequired;
import com.qinggeng.project.api.security.utils.ApiUtils;
import com.qinggeng.project.api.service.IApiMemberService;
import com.qinggeng.project.api.utils.AMapUtils;
import com.qinggeng.project.api.utils.PhoneNumberUtils;
import com.qinggeng.project.system.domain.*;
import com.qinggeng.project.system.service.*;
import com.qinggeng.project.tool.sms.service.ISysSmsService;
import io.swagger.annotations.*;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.qinggeng.project.api.security.utils.ApiUtils.getIsLogin;
import static com.qinggeng.project.api.security.utils.ApiUtils.getUserId;
import static com.qinggeng.project.system.service.impl.UserMapServiceImpl.USER_DISTRICT_KEY;

@Api(tags = "用户模块")
@RestController
@RequestMapping("${apiPath}/user")
public class ApiUserController extends BaseController {



    @Autowired
    private IUserAddressService userAddressService;

    @Autowired
    private ISysLeagueService sysLeagueService;

    @Autowired
    private IApiMemberService memberService;

    @Autowired
    private ISysSmsService smsService;

    @Autowired
    private IUserCartService userCartService;

    @Autowired
    private IUserCollectService userCollectService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IOrdersEvaluateService ordersEvaluateService;

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private IUserWalletService userWalletService;

    @Autowired
    private IUserLocationService userLocationService;

    @Autowired
    private IShopService shopService;

    @Autowired
    private IUserConsumeService userConsumeService;

    @Autowired
    private IUserWithdrawService userWithdrawService;

    @Autowired
    private IUserMessageService userMessageService;

    @Autowired
    private IOrdersGoodsService ordersGoodsService;

    @Autowired
    private IUserGiftService userGiftService;

    @Autowired
    private ISysRegionService sysRegionService;

    @Autowired
    private IGoodsActiviyService goodsActiviyService;

    @Autowired
    private UserMessageIconService userMessageIconService;

    @Autowired
    private IUserAliasService userAliasService;

    @Autowired
    private IUserActivityService userActivityService;
    @Autowired
    private IUserGoodsLimitRecordService userGoodsLimitRecordService;

    @Autowired
    private IUserMapService userMapService;


    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private MemberService vipMemberService;

    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    @ApiOperation("收货地址列表")
    @GetMapping("/addressList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true),
            @ApiImplicitParam(name = "shopId", value = "订单选择时传入", dataType = "Long", paramType = "query", required = false),
    })
    public AjaxResult addressList(Long shopId) {
        UserAddress where = new UserAddress();
        where.setUserId(ApiUtils.getUserId());
        where.setDelFalg("10");
        where.setShopId(shopId);
        return AjaxResult.success(userAddressService.selectUserAddressList(where));
    }

    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    @ApiOperation("收货地址删除")
    @PostMapping("/addressDel")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true),
            @ApiImplicitParam(name = "addressId", value = "收货地址ID", dataType = "Long", paramType = "query"),
    })
    public AjaxResult addressDel(Long addressId) {
        UserAddress userAddress = userAddressService.selectUserAddressById(addressId);
        userAddress.setDelFalg("20");
        return toAjax(userAddressService.updateUserAddress(userAddress));
    }

    @ApiOperation("城市列表")
    @GetMapping("/cityList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true),
            @ApiImplicitParam(name = "level", value = "地区层级 1=省 2=市 3=县/区", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "地区名", dataType = "String", paramType = "query"),
    })
    public AjaxResult cityList(Long level,String name) {
        //创建地区表对象
        SysRegion sysRegion = new SysRegion();
        //根据地区等级查询
        if (level !=null) {
            if (name == null) {
                //设置参数
                sysRegion.setLevel(level);
                //查询
                List<SysRegion> sysRegions = sysRegionService.selectSYsRegionListByLevel(sysRegion);
                //存储对应要求的城市集合
                List<HashMap<String, Object>> sysRegionList = Lists.newArrayList();
                //创建list存储热门城市
                List<SysRegion> hotlist = Lists.newArrayList();
                for (SysRegion region : sysRegions) {
                    if (region.getHot()==1){
                        hotlist.add(region);
                    }
                }
                HashMap<String, Object> hotMap = Maps.newHashMap();
                hotMap.put("first","0");
                hotMap.put("citys",hotlist);
                sysRegionList.add(hotMap);


                //存储首字母开头的城市集合
                for (char c = 'A'; c <= 'Z'; c++) {
                    List<SysRegion> list = Lists.newArrayList();
                    for (SysRegion region : sysRegions) {

                        if (String.valueOf(c).equals(region.getFirst())) {
                            list.add(region);
                        }
                    }
                    HashMap<String, Object> sysRegionMap = Maps.newHashMap();
                    sysRegionMap.put("first", c);
                    sysRegionMap.put("citys", list);
                    sysRegionList.add(sysRegionMap);
                }
                return AjaxResult.success(sysRegionList);

            }
        }
        //根据名称模糊查询城市
        if (name != null){
            sysRegion.setName(name);
            sysRegion.setLevel(2L);
            List<SysRegion> sysRegions = sysRegionService.selectSysRegionList(sysRegion);
            return AjaxResult.success(sysRegions);
        }

        return AjaxResult.error("查询不到");
    }

    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    @ApiOperation("收货地址编辑")
    @PostMapping("/addressEdit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    public AjaxResult addressEdit(UserAddress userAddress) {
        if (!PhoneNumberUtils.isMobile(userAddress.getAddressPhone())){
            return AjaxResult.error("手机号码格式错误，请重新输入", ShowTypeEnum.用户.getValue());
        }
        userAddress.setUserId(ApiUtils.getUserId());
        Shop shop = shopService.selectShopByLocation(userAddress.getAddressLng(), userAddress.getAddressLat());
        if (shop == null){
            return AjaxResult.error("当前城市无商户",ShowTypeEnum.用户.getValue());
        }
        userAddress.setShopId(shop.getId());

        //处理多默认情况
        if (userAddress.getStatus().equals(CommonEnum.STATUS_20.getValue())){
            userAddressService.updateUserAddressStatus(ApiUtils.getUserId(),CommonEnum.STATUS_10.getValue());
        }

        if (userAddress.getAddressId() != null) {
            return toAjax(userAddressService.updateUserAddress(userAddress));
        } else {
            return toAjax(userAddressService.insertUserAddress(userAddress));
        }
    }


    @ApiOperation("申请加盟")
    @PostMapping("/leagueAdd")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记")
    })
    @CrossOrigin
    @Log(title = "加盟信息", businessType = BusinessType.INSERT)
    @LoginRequired(must = false,role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult leagueAdd(SysLeague sysLeague) {

        if(ApiUtils.getIsLogin()){
            sysLeague.setUserId(ApiUtils.getUserId());
        }
        return toAjax(sysLeagueService.insertSysLeague(sysLeague));
    }


    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    @ApiOperation("设置密码")
    @PostMapping("/bindPwd")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", paramType = "query"),
    })
    public AjaxResult bindPwd(String password) {
        SysUser sysUser = ApiUtils.getApiUser().getUser();
        if (StringUtils.isEmpty(password)) {
            return AjaxResult.error("请输入密码",ShowTypeEnum.用户.getValue());
        }
        if (sysUser.getPwdSet().equals("20")) {
            return AjaxResult.success("已绑定密码",ShowTypeEnum.用户.getValue());
        }
        return toAjax(memberService.updatePassWord(sysUser.getPhonenumber(), password, sysUser.getUserType()));
    }


    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    @ApiOperation("修改密码")
    @PostMapping("/updatePwd")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true),
            @ApiImplicitParam(name = "oldPwd", value = "原密码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "newPwd", value = "新密码", dataType = "String", paramType = "query"),
    })
    public AjaxResult updatePwd(String oldPwd, String newPwd) {
        SysUser sysUser = ApiUtils.getApiUser().getUser();
        if (!ApiUtils.matchesPassword(oldPwd, sysUser.getPassword())) {
            return AjaxResult.error("原密码错误",ShowTypeEnum.用户.getValue());
        }
        return toAjax(memberService.updatePassWord(sysUser.getPhonenumber(), newPwd, sysUser.getUserType()));
    }




    @CrossOrigin
    @ApiOperation("获取用户信息")
    @GetMapping("/getInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    @LoginRequired(must = true)
    public AjaxResult getInfo() {
        LoginUser loginUser = ApiUtils.getApiUser();
        String phone=loginUser.getUser().getPhonenumber();
        if (StringUtils.isNotEmpty(phone)) {
            loginUser.getUser().setPhonenumber(phone);
        }
        if (StringUtils.isEmpty(loginUser.getUser().getAvatar())){
            loginUser.getUser().setAvatar(UserConstants.DEFAULT_AVATAR);
        }
        Map<String, Object> data = Maps.newHashMap();
        data.put("user", loginUser.getUser());
        if (ApiUtils.getApiRole().equals(ApiUtils.DEFAULT_ROLE_USER)){
            Orders ordersWhere = new Orders();
            ordersWhere.setUserId(ApiUtils.getUserId());
            //待付款
            ordersWhere.setOrdersIndex(1);
            data.put("payOrdersNum",ordersService.selectOrdersCount(ordersWhere));
            //待发货
            ordersWhere.setOrdersIndex(2);
            data.put("distOrdersNum",ordersService.selectOrdersCount(ordersWhere));
            //待收货
            ordersWhere.setOrdersIndex(3);
            data.put("selfOrdersNum",ordersService.selectOrdersCount(ordersWhere));
            //待评价
            ordersWhere.setOrdersIndex(4);
            data.put("evalOrdersNum",ordersService.selectOrdersCount(ordersWhere));
            //最近的订单
            Orders orders = ordersService.selectOrdersByDefaultUserId(ApiUtils.getUserId());
            if (orders != null){
                orders.setGoodsList(ordersGoodsService.selectOrderGoodListByOrdersId(orders.getOrdersId()));
            }
            data.put("orders",orders);
            //拉新活動
            data.put("userInvitActivity",userActivityService.getUserActivityInvitVO());
            Long courierId = sysUserService.selectUserIdByPhoneNumberAndUserType(phone, UserTypeEnum.COURIER.getCode());
            data.put("courierId",courierId==null?0:courierId);
            //用户购物车所有商品的数量
            data.put("goodsNum",userCartService.selectUserCartGoodsNumByUserId(ApiUtils.getUserId()));
            //是否是团长
            data.put("isChief",sysUserService.isChief(phone));
            //是否是vip
            data.put("vip",vipMemberService.isVip(ApiUtils.getUserId()));
            data.put("svip",vipMemberService.isSVip(ApiUtils.getUserId()));

        }
        if(ApiUtils.getApiRole().equals(ApiUtils.DEFAULT_ROLE_COURIER)){
            data.put("wallet",userWalletService.selectUserWalletByUserId(ApiUtils.getUserId()));
        }

        UserMessage messageWhere = new UserMessage();
        messageWhere.setUserId(ApiUtils.getUserId());
        messageWhere.setRead(false);
        data.put("messageNum",userMessageService.selectUserMessageCount(messageWhere));
        //1使用 0不实用
        data.put("wxpay","1");
        data.put("alipay","1");
        return AjaxResult.success(data);
    }


    @LoginRequired
    @ApiOperation("修改用户信息")
    @PostMapping("/updateInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true),
            @ApiImplicitParam(name = "nickName", value = "昵称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "avatar", value = "头像路径", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "workStatus", value = "工作状态 10=未开启 20=已开启 骑手端有效", dataType = "String", paramType = "query"),
    })
    public AjaxResult updateInfo(String nickName, String avatar,String workStatus) {
        SysUser user = ApiUtils.getApiUser().getUser();
        user.setNickName(nickName);
        user.setAvatar(avatar);
        if (ApiUtils.getApiRole().equals(ApiUtils.DEFAULT_ROLE_COURIER) && StringUtils.isNotEmpty(workStatus)){
            //判断是否
            if (workStatus.equals(CommonEnum.STATUS_10.getValue())){
                if (ordersService.selectOrdersDiscDtoCount(ApiUtils.getUserId(),1,null,null) > 0){
                    return AjaxResult.success("有未完成的订单无法下班",ShowTypeEnum.用户.getValue(),0);
                }
            }
            user.setWorkStatus(workStatus);
        }
        return AjaxResult.success("修改成功",ShowTypeEnum.用户.getValue(),memberService.updateMember(user));
    }

    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    @ApiOperation("修改手机号")
    @PostMapping("/updatePhone")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true),
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", dataType = "String", paramType = "query"),
    })
    public AjaxResult updatePhone(String phone, String code) {
        SysUser user=memberService.selectByPhone(phone,UserTypeEnum.MEMBER.getCode());
        if(user!=null){
            return AjaxResult.error("手机号码已被其他用户绑定！",ShowTypeEnum.用户.getValue());
        }
        String checkCode = smsService.getCode(phone, "updPhone");
        if (StringUtils.isEmpty(checkCode) || !code.equals(checkCode)) {
            return AjaxResult.error("验证码错误",ShowTypeEnum.用户.getValue());
        }
        return toAjax(memberService.updatePhone(ApiUtils.getUserId(), phone));
    }

    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    @ApiOperation("收藏列表")
    @GetMapping("/collectList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    public AjaxResult collectList() {
        startPage();
        UserCollect where =new UserCollect();
        where.setUserId(ApiUtils.getUserId());
        where.setStatus("10");
        List<GoodsCollectDto> goodsDtoList = userCollectService.selectUserCollectGoodsList(where);
        return AjaxResult.success(goodsDtoList);
    }

    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    @ApiOperation("取消收藏")
    @PostMapping("/cancelCollect")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "collectId", value = "收藏ID", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    public AjaxResult cancelCollect(Long collectId){
        UserCollect userCollect = userCollectService.selectUserCollectById(collectId);
        userCollect.setStatus("20");
        return toAjax(userCollectService.updateUserCollect(userCollect));
    }


    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    @ApiOperation("购物车列表")
    @GetMapping("/cartList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "shopId", value = "商户ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    public AjaxResult cartList(Long shopId) {
        //startPage();
        UserCart where = new UserCart();
        where.setUserId(ApiUtils.getUserId());
        where.setShopId(shopId);
        List<CartDto> cartDtoList = userCartService.selectUserCartDtoList(where);

        return AjaxResult.success(cartDtoList);
    }

    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    @ApiOperation("修改购物车数量")
    @PostMapping("/cartEdit")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cartId", value = "购物车ID", dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "num", value = "数量", dataType = "Integer", paramType = "path"),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    public AjaxResult cartEdit(Long cartId,Integer num){
        UserCart userCart = userCartService.selectUserCartById(cartId);
        Long goodsId=userCart.getGoodsId();

        GoodsInfoDto goodsInfoDto = goodsService.selectGoodsDtoById(goodsId, userCart.getShopId());
        if (goodsInfoDto == null){
            return AjaxResult.error("商品不存在");
        }

        if (goodsInfoDto.getKeepNum() < num){
            return AjaxResult.error("已被抢光无法添加",ShowTypeEnum.用户.getValue());
        }
        userGoodsLimitRecordService.checkIsGoodsLimit(goodsId,0,num);
        userCart.setGoodsNum(num);
        int rows=userCartService.updateUserCart(userCart);
        if(rows<=0){
            return AjaxResult.error("修改失败！");
        }
        //用户购物车所有商品的数量
        Map<String,Object> data=Maps.newHashMap();
        data.put("goodsNum",userCartService.selectUserCartGoodsNumByUserId(ApiUtils.getUserId()));
        return AjaxResult.success("修改成功！",data);
    }

    /**
     * 删除用户购物车信息
     */
    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    @ApiOperation("购物车删除")
    @PostMapping("/cartDel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cartIds", value = "购物车ID 逗号分隔", dataType = "String", paramType = "path"),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    public AjaxResult cartDel( String cartIds){
        Long[] ids= (Long[]) ConvertUtils.convert(cartIds.split(","),Long.class);
        int rows=userCartService.deleteUserCartByIds(ids);
        if(rows<=0){
            return AjaxResult.error("删除失败！");
        }
        //用户购物车所有商品的数量
        Map<String,Object> data=Maps.newHashMap();
        data.put("goodsNum",userCartService.selectUserCartGoodsNumByUserId(ApiUtils.getUserId()));
        return AjaxResult.success("删除成功",data);
    }

    /**
     * 评价列表
     * @return
     */
    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    @ApiOperation("评价列表")
    @GetMapping("/evaluateList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true),
    })
    public AjaxResult evaluateList(){
        startPage();
        OrdersEvaluate where = new OrdersEvaluate();
        where.setUserId(ApiUtils.getUserId());
        where.setDelFlag("0");
        return AjaxResult.success(ordersEvaluateService.selectOrdersEvaluateUserDtoList(where));
    }

    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    @ApiOperation("评价删除")
    @GetMapping("/evaluateDel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ordersId", value = "订单ID", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true),
    })
    public AjaxResult evaluateDel(Long ordersId){
        OrdersEvaluate where =new OrdersEvaluate();
        where.setOrdersId(ordersId);
        List<OrdersEvaluate> ordersEvaluates = ordersEvaluateService.selectOrdersEvaluateList(where);
        for (OrdersEvaluate ordersEvaluate : ordersEvaluates) {
            ordersEvaluate.setDelFlag("2");
            ordersEvaluateService.updateOrdersEvaluate(ordersEvaluate);
        }
        return AjaxResult.success();
    }

    /**
     * 添加位置信息
     * @return
     */
    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_COURIER)
    @ApiOperation("添加位置信息 5秒一次")
    @PostMapping("/addLocation")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lng", value = "精度", dataType = "Float", paramType = "query", required = true),
            @ApiImplicitParam(name = "lat", value = "纬度", dataType = "Float", paramType = "query", required = true),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true),
    })
    public AjaxResult addLocation(Float lng,Float lat){
        userLocationService.deleteUserLocationById(ApiUtils.getUserId());
        return toAjax(userLocationService.insertUserLocation(new UserLocation(ApiUtils.getUserId(),lng,lat)));
    }


    @ApiOperation("收支明细")
    @GetMapping("/userConsume")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    @LoginRequired
    public AjaxResult userConsume(){
        startPage();
        UserConsume where = new UserConsume();
        where.setUserId(ApiUtils.getUserId());
        List<UserConsume> userConsumeList = userConsumeService.selectUserConsumeList(where);
        return AjaxResult.success(userConsumeList);
    }

    @ApiOperation("添加提现记录")
    @PostMapping("/addWithdraw")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "price", value = "金额", dataType = "BigDecimal", paramType = "query", required = true),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_COURIER)
    public AjaxResult addWithdraw(BigDecimal price){
        return toAjax(userWithdrawService.addWithdraw(ApiUtils.getUserId(),price));
    }

    @ApiOperation("消息列表")
    @GetMapping("/messageList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "newsCategory", value = "消息类别 10=物流消息 20=活动消息", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    @LoginRequired
    public AjaxResult messageList(String newsCategory){
        startPage();
        //物流消息
        if (newsCategory.equals("10")) {
            UserMessage where = new UserMessage();
            where.setUserId(ApiUtils.getUserId());
            where.setMessageCategory(newsCategory);
            return AjaxResult.success(userMessageService.listMessageListDto(where));

        }
        //商品活动
        if (newsCategory.equals("20")){
            GoodsActivity goodsActivity = new GoodsActivity();
            //查询所有商品活动
            List<GoodsActivity> goodsActivities = goodsActiviyService.selectGoodsActivity(goodsActivity);
            ArrayList<MessageListDto> messageDtos = Lists.newArrayList();
            for (GoodsActivity activity : goodsActivities) {
                if (activity == null){
                    activity = new GoodsActivity();
                }
                GoodsActivityDto goodsActivityDto = GoodsActivityDto.getGoodsActivityDto(activity);
                MessageListDto messageDto = new MessageListDto();
                messageDto.setMessageId(goodsActivityDto.getActivityId());
                messageDto.setMessageTitle(goodsActivityDto.getActivityName());
                messageDto.setMessageIcon(goodsActivityDto.getActivityIcon());
                messageDto.setMessageTime(DateUtils.getAutoTime(goodsActivityDto.getCreateTime()));
                messageDto.setMessageContent(goodsActivityDto.getActivityContent());
                messageDto.setMessageUrl(goodsActivityDto.getReturnUrl());
                messageDto.setMessageImage(goodsActivityDto.getActivityImage());
                messageDto.setIsActivity("0");
                messageDtos.add(messageDto);
            }
            return  AjaxResult.success(messageDtos);
        }
        return AjaxResult.error("系统异常");

    }
    @ApiOperation("骑手消息列表")
    @GetMapping("/distMessageList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    @LoginRequired
    public AjaxResult distMessageList(){
        try {
            startPage();
            UserMessage where = new UserMessage();
            where.setUserId(ApiUtils.getUserId());
            List<UserMessage> userMessageList = userMessageService.selectUserMessageMemberList(where);

            //消息集合
            List<Map<String,String>> data = Lists.newArrayList();
            Orders orders = null;
            for (UserMessage userMessage : userMessageList) {
//                if (userMessage.getMessageType().equals(MessageTypeEnum.提现消息.getValue())){
//                    userMessage.setWithdraw(userWithdrawService.selectUserWithdrawById(userMessage.getFkId()));
//                }
                if (userMessage.getMessageType().equals(MessageTypeEnum.订单消息.getValue())) {
                    Map<String, String> map = Maps.newHashMap();
                    orders = ordersService.selectOrdersById(userMessage.getFkId());
                    if (orders == null) continue;
                    map.put("ordersId",String.valueOf(orders.getOrdersId()));
                    map.put("ordersNo",orders.getOrdersNo());
                    //消息标题
                    map.put("fk_mark",userMessage.getFkMark());
                    //消息内容
                    map.put("fk_content",userMessage.getFkContent());
                    //110骑手新订单
                    map.put("statusCode",userMessage.getStatusCode());
                    map.put("createTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,userMessage.getCreateTime()));
                    data.add(map);
                }
                if (!userMessage.getRead()) {
                    userMessage.setRead(true);
                    userMessageService.updateUserMessage(userMessage);
                }
            }
            return AjaxResult.success(data);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }


    }
    @ApiOperation("我的礼包")
    @GetMapping("/userGiftList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult userGiftList(){
        startPage();
        UserGift where = new UserGift();
        where.setUserId(ApiUtils.getUserId());
        return AjaxResult.success(UserGiftDto.newsList(userGiftService.selectUserGiftList(where)));
    }

    @ApiOperation("保存消息推送别名")
    @GetMapping("/userAlias")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "alias", value = "消息推送别名", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = false)
    })
    @LoginRequired(must=false,role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult updateUserAlias(String alias){
        int rows=0;
        if(getIsLogin()){
            //将消息推送别名和用户ID进行绑定
            LoginUser user=ApiUtils.getApiUser();
            rows=userAliasService.setLoginUserAlias(alias,ApiUtils.getUserId(),user.getUser().getUserType(),user.getToken());
        }else if(StringUtils.isNotEmpty(alias)){
            UserAlias userAlias=userAliasService.selectUserAliasByAlias(alias);
            if(userAlias==null){                ;
                rows=userAliasService.insertUserAlias(new UserAlias(alias));
            }
        }
        return AjaxResult.success(rows);
    }

    @ApiOperation("删除消息")
    @PostMapping("delMessage")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "messageId", value = "消息Id", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = false)
    })
    @LoginRequired(must=true,role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult delMessage(String messageId){
        boolean bl=userMessageService.delMessage(messageId);
        if (bl){
            return AjaxResult.success("删除成功",ShowTypeEnum.用户.getValue());
        }
        return AjaxResult.error("删除失败",ShowTypeEnum.用户.getValue());
    }

    @ApiOperation("用户导航")
    @GetMapping("map")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lng", value = "精度", dataType = "Float", paramType = "query", required = true),
            @ApiImplicitParam(name = "lat", value = "纬度", dataType = "Float", paramType = "query", required = true),
            @ApiImplicitParam(name = "location",value = "场景（0=首页 1=个人中心）",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name="screen",value = "筛选（0=不筛选 1=筛选）",dataType = "String",paramType = "query"),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = false)
    })
    @LoginRequired(must = false)
    public AjaxResult userMap(Float lng,Float lat,
            @RequestParam(name = "location",defaultValue = "1") String location,
            @RequestParam(name = "screen" ,defaultValue = "0") String screen){
        UserMap where=new UserMap();
        where.setLocation(location);
        if("1".equals(screen)){
            where.setScreen("1");
        }
        return AjaxResult.success(userMapService.listUserMap(AMapUtils.getDistrict(lng,lat),where));
    }

}
